package com.qlzb.taskmanagement.utils;

import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


/**
 * @(#)DateUtil.java
 *
 * 系统名称：
 * 版本号：      1.0
 *
 * Copyright (c)     All rights reserved
 *
 * 作者: 	  xiaotao
 * 创建日期:    2015年12月1日
 *
 * 包名：
 * 功能描述：
 * 公用方法描述：
 *
 * 修改人：
 * 修改日期：
 * 修改原因：
 *
 **/
public class DateUtil {
	private static Logger logger = LoggerFactory.getLogger(DateUtil.class);
	private final static String Month_FORMAT = "yyyyMM";


    public static String objToStr(String str){
    	if(str==null || str.isEmpty() || str.trim().length()==0){
    		return "";
    	}
    	return str.trim();
    }

	/**
	 * @description:将时间转为字符串，并且格式为yyyy-MM-dd
	 * @param:
	 * @return: String
	 */
	public static String parseDate(Date date){
		if(date != null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			return sdf.format(date);
		}else{
			return null;
		}
	}
	/**
	 * @description:将时间转为前两年字符串，并且格式为yyyy-MM-dd
	 * @param:
	 * @return: String
	 */
	public static String parseDateYearAgo(Date date){
		if(date != null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal=Calendar.getInstance();
			cal.add(Calendar.YEAR, -2);
			return sdf.format(cal.getTime());
		}else{
			return null;
		}
	}

	/**
	 * @description:将时间转为字符串，并且格式为yyyy-MM-dd HH:mm
	 * @param:
	 * @return: String
	 */
	public static String parseDateTimeToMin(Date date){
		if(date != null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
			return sdf.format(date);
		}else{
			return null;
		}
	}

	/**
	 * @description:将时间转为字符串，并且格式为yyyy-MM-dd HH:mm:ss
	 * @param:
	 * @return: String
	 */
	public static String parseDateTimeToSec(Date date){
		if(date != null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.format(date);
		}else{
			return null;
		}
	}

	/**
	 * @description：通过同步的方式给上传的文件重新获取名称。以时间解析得到.用于文件名的前缀名
	 * @param
	 * @return：String
	 * @方法编号：
	 */
	public synchronized  static String getTimeForFileName(){
		try {
			Thread.sleep(1L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssS");
		return sdf.format(date);

	}

	/**
	 * @description：生成年月
	 * @param
	 * @return：String
	 */
	public static String getCurrYearMonth(int imonth) {
		Calendar c= new GregorianCalendar();
		c.setTime(new Date());
		if(imonth!=0)
        c.add(Calendar.MONTH, imonth);
		SimpleDateFormat formatter = new SimpleDateFormat(Month_FORMAT);
		return formatter.format((c.getTime()));

	}
	/**
	 * @description：生成年月
	 * @param
	 * @return：String
	 */
	public static String getCurrYearMonth() {
		Calendar c= new GregorianCalendar();
		c.setTime(new Date());
		SimpleDateFormat formatter = new SimpleDateFormat(Month_FORMAT);
		return formatter.format((c.getTime()));

	}


	/**
	 *description:生成年
	 *@return  String
	 */
	public static String getCurrYear() {
		Calendar c= new GregorianCalendar();
		c.setTime(new Date());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		return formatter.format((c.getTime()));

	}

	/**
	 *description:生成月
	 *@return  String
	 */
	public static String getCurrMoonth() {
		Calendar c= new GregorianCalendar();
		c.setTime(new Date());
		SimpleDateFormat formatter = new SimpleDateFormat("MM");
		return formatter.format((c.getTime()));

	}
	/**
	 *description:根据date  得到月
	 *@return  String
	 */
	public static String getDateMonth(Date date) {
		Calendar c= new GregorianCalendar();
		c.setTime(date);
		SimpleDateFormat formatter = new SimpleDateFormat("MM");
		return formatter.format((c.getTime()));

	}
	/**
	 *description:根据date  得到年
	 *@return  String
	 */
	public static String getDateYear(Date date) {
		Calendar c= new GregorianCalendar();
		c.setTime(date);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		return formatter.format((c.getTime()));
	}

	/**
	 * @description:字符串转为时间
	 */
	public static Date parseDateTimeToMin(String str){
		if(str !=null && !"".equals(str)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date d=null;
			try {
				d=sdf.parse(str);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return d;
		}else{
			return null;
		}
	}

	/**
	 * @description:字符串转为时间
	 */
	public static Date parseDate(String str){
		if(str !=null && !"".equals(str)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date d=null;
			try {
				d=sdf.parse(str);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return d;
		}else{
			return null;
		}
	}
	/**
	 * @description:字符串转为时间
	 */
	public static Date parseDate(String str,String pattern){
		if(str !=null && !"".equals(str)){
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			Date d=null;
			try {
				d=sdf.parse(str);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return d;
		}else{
			return null;
		}
	}
	/**
	 * @description:日期加天数得到新的日期
	 */
    public static Date addDate(Date d,Integer day){
    	if(d != null){
    		Calendar cal=Calendar.getInstance();
    		cal.setTime(d);
    		cal.add(Calendar.DATE, day);
    		Date date=cal.getTime();
    		return date;
    	}else{
    		return null;
    	}

	}

    /**
     * @description: 日期加分钟得到新的日期
     */
    public static Date addMinutes(Date d, Integer minu) {
    	if(d != null) {
    		Calendar cal=Calendar.getInstance();
    		cal.setTime(d);
    		cal.add(Calendar.MINUTE, minu);
    		Date date=cal.getTime();
    		return date;
    	}else{
    		return null;
    	}
    }

    /**
	 * @description:将时间转为字符串，并且格式为yyyy/MM/dd HH:mm:ss
	 */
	public static String parseDateTimeToStr(Date date){
		if(date != null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			return sdf.format(date);
		}else{
			return null;
		}
	}

	 /**
	 * @description:将时间转为字符串，并且格式为dateFormat
	 * @param: sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
	 * @return: String
	 */
	public static String parseDateTimeToStrByDateFormat(Date date,String dateFormat){
		SimpleDateFormat sdf=new SimpleDateFormat(dateFormat);
		if(date != null){
			return sdf.format(date);
		}else{
			return sdf.format(new Date());
		}
	}

	/**
	 * @description:字符串转为时间
	 */
	public static Date parseDateTimeToDate(String str,String dateFormat){
		if(str !=null && !"".equals(str)){
			SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
			Date d=null;
			try {
				d=sdf.parse(str);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return d;
		}else{
			return null;
		}
	}



	 /**
	 * @description:获取前一天是周几
	 * @param: b
	 * @return:
	 */
	public static Integer getLastDayOfWeek(){
		Calendar cal=Calendar.getInstance();
		int dayOfWeek=cal.get(Calendar.DAY_OF_WEEK);
		Integer weekDay = null;
		switch (dayOfWeek){
		     case 1:
			   weekDay=6;
			   break;
			  case 2:
		       weekDay=7;
			   break;
			  case 3:
			   weekDay=1;
			   break;
			  case 4:
			   weekDay=2;
			   break;
			  case 5:
			   weekDay=3;
			   break;
			  case 6:
			   weekDay=4;
			   break;
			  case 7:
			   weekDay=5;
			   break;
			  }
		return weekDay;
	}
	/**
	 * @description:获取当前日期是周几
	 * @param:
	 * @return:
	 */
	public static Integer getCurrentDayOfWeek(){
		Calendar cal=Calendar.getInstance();
		int dayOfWeek=cal.get(Calendar.DAY_OF_WEEK);
		Integer weekDay = null;
		switch (dayOfWeek){
		     case 1:
			   weekDay=7;
			   break;
			  case 2:
		       weekDay=1;
			   break;
			  case 3:
			   weekDay=2;
			   break;
			  case 4:
			   weekDay=3;
			   break;
			  case 5:
			   weekDay=4;
			   break;
			  case 6:
			   weekDay=5;
			   break;
			  case 7:
			   weekDay=6;
			   break;
			  }
		return weekDay;
	}

	/**
	 * @description:获取昨天的日期
	 */
	  public static String getYesterday(){
		  Calendar   cal   =   Calendar.getInstance();
		  cal.add(Calendar.DATE,   -1);
		  String yesterday = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());
		  return yesterday;
	  }


	  /**
	   * 得到某年某月的第一天
	   *
	   * @param year
	   * @param month
	   * @return
	   */
	  public static String getFirstDayOfMonth(int year, int month) {
	      Calendar cal = Calendar.getInstance();
	      cal.set(Calendar.YEAR, year);
	      cal.set(Calendar.MONTH, month-1);
	      cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
	      return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
	  }

	  /**
	   * 得到某年某月的最后一天
	   *
	   * @param year
	   * @param month
	   * @return
	   */
	  public static String getLastDayOfMonth(int year, int month) {
	      Calendar cal = Calendar.getInstance();
	      cal.set(Calendar.YEAR, year);
	      cal.set(Calendar.MONTH, month-1);
	      cal.set(Calendar.DAY_OF_MONTH, 1);
	      int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
	      cal.set(Calendar.DAY_OF_MONTH, value);
	      return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
	  }

	/**
	 * @description:获取当前是几点
	 * @param:
	 * @return:
	 */
	public static Integer getCurrentHourOfDay(){
		Calendar cal=Calendar.getInstance();
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		return hour;
	}

	/**
	 * @description:获取当前是几点
	 */
	public static Date findNextDay(String str,Integer dayNum){
		String[] strArr = str.split(",");
		Integer addNum=null;
		for(String s:strArr){
			addNum=new Integer(s);
			if(dayNum<addNum){
				return addDate(new Date(), addNum-dayNum);
			}
		}
		addNum=new Integer(strArr[0]);
		return addDate(new Date(), 7-dayNum+addNum);
	}
	/**
	 * @description:获取当前是几点
	 */
	public static String showWeekDay(String str){
		String[] strArr = str.split(",");
		Integer addNum=null;
		String dayStr="";
		String charStr = "";
		for(String s:strArr){
			 addNum=new Integer(s);
			 if(addNum==1){
				 dayStr+=charStr+"周一";
			 }else if(addNum==2){
				 dayStr+=charStr+"周二";
			 }else if(addNum==3){
				 dayStr+=charStr+"周三";
			 }else if(addNum==4){
				 dayStr+=charStr+"周四";
			 }else if(addNum==5){
				 dayStr+=charStr+"周五";
			 }else if(addNum==6){
				 dayStr+=charStr+"周六";
			 }else if(addNum==7){
				 dayStr+=charStr+"周日";
			 }
			 charStr = "、";
		}
		return dayStr;
	}
	/**
	 * @description:月份转化为字母
	 */
	public static String monthToLetter(Date date){
		String dateMonth = getDateMonth(date);
		if ("01".equals(dateMonth)) {
			return "A";
		}else if("02".equals(dateMonth)){
			return "B";
		}else if("03".equals(dateMonth)){
			return "C";
		}else if("04".equals(dateMonth)){
			return "D";
		}else if("05".equals(dateMonth)){
			return "M";
		}else if("06".equals(dateMonth)){
			return "N";
		}else if("07".equals(dateMonth)){
			return "L";
		}else if("08".equals(dateMonth)){
			return "R";
		}else if("09".equals(dateMonth)){
			return "S";
		}else if("10".equals(dateMonth)){
			return "X";
		}else if("11".equals(dateMonth)){
			return "Y";
		}else{
			return "Z";
		}
	}

	/**
	 * @description:获取链两个日期间的更新数量
	 */
	public static int findWeekDayNum(Date beginDate,Date endDate,String str){
        int n = 0;
      	Calendar cal = Calendar.getInstance();
        cal.setTime(beginDate);
        while(cal.getTime().compareTo(endDate)<=0){
			int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
			if(w==0) w=7;
			if(str.indexOf(w+"")>=0){
				n++;
			}
			cal.add(cal.DAY_OF_MONTH, 1);
        }
        return n;
	}

	//判断两个时间点是否间隔time分  false表示间隔未超过time分钟
	public static boolean dateInterval(String start, String end, int time) throws ParseException{
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(start==null || end==null ){
			return false;
		}else{
			Date startDate = format1.parse(start);
			Date endDate = format1.parse(end);
			long  dateInterval=(endDate.getTime() - startDate.getTime()) / (1000 * 60);
			return 	dateInterval	 >= time;

		}
	}
	/**
	 * 得到当前日期字符串 格式（yyyy-MM-dd）
	 */
	public static String getDate() {
		return getDate("yyyy-MM-dd");
	}

	/**
	 * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String getDate(String pattern) {
		return DateFormatUtils.format(new Date(), pattern);
	}


	/**
	 * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String formatDate(Date date, Object... pattern) {
		String formatDate = null;
		if (pattern != null && pattern.length > 0) {
			formatDate = DateFormatUtils.format(date, pattern[0].toString());
		} else {
			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
		}
		return formatDate;
	}

	/**
	 * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String formatDateTime(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到当前时间字符串 格式（HH:mm:ss）
	 */
	public static String getTime() {
		return formatDate(new Date(), "HH:mm:ss");
	}

	/**
	 * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String getDateTime() {
		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到当前年份字符串 格式（yyyy）
	 */
	public static String getYear() {
		return formatDate(new Date(), "yyyy");
	}

	/**
	 * 得到当前月份字符串 格式（MM）
	 */
	public static String getMonth() {
		return formatDate(new Date(), "MM");
	}

	/**
	 * 得到当天字符串 格式（dd）
	 */
	public static String getDay() {
		return formatDate(new Date(), "dd");
	}

	/**
	 * 得到当前星期字符串 格式（E）星期几
	 */
	public static String getWeek() {
		return formatDate(new Date(), "E");
	}

	/**
	 * 获取过去的天数
	 *
	 * @param date
	 * @return
	 */
	public static long pastDays(Date date) {
		long t = new Date().getTime() - date.getTime();
		return t / (24 * 60 * 60 * 1000);
	}

	/**
	 * 获取过去的小时
	 *
	 * @param date
	 * @return
	 */
	public static long pastHour(Date date) {
		long t = new Date().getTime() - date.getTime();
		return t / (60 * 60 * 1000);
	}

	/**
	 * 获取过去的分钟
	 *
	 * @param date
	 * @return
	 */
	public static long pastMinutes(Date date) {
		long t = new Date().getTime() - date.getTime();
		return t / (60 * 1000);
	}

	/**
	 * 转换为时间（天,时:分:秒.毫秒）
	 *
	 * @param timeMillis
	 * @return
	 */
	public static String formatDateTime(long timeMillis) {
		long day = timeMillis / (24 * 60 * 60 * 1000);
		long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
		long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
		return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
	}

	/**
	 * 获取两个日期之间的天数
	 *
	 * @param before
	 * @param after
	 * @return
	 */
	public static double getDistanceOfTwoDate(Date before, Date after) {
		long beforeTime = before.getTime();
		long afterTime = after.getTime();
		return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
	}

	/**
	 * 获取两个时间的时间差
	 *
	 * @param before
	 * @param after
	 * @return
	 * @author qiang.liu 2016年11月1日 下午2:04:21
	 */
	public static long getDoubleDifference(Date before, Date after) {
		return after.getTime() - before.getTime();

	   /*long day=l/(24*60*60*1000);
       long hour=(l/(60*60*1000)-day*24);
	   long min=((l/(60*1000))-day*24*60-hour*60);
	   long s=(l/1000-day*24*60*60-hour*60*60-min*60);
	   logger.info(""+day+"天"+hour+"小时"+min+"分"+s+"秒"); */
	}

	/**
	 * 获取两个日期之间的月数
	 *
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException
	 * @author qiang.liu 2016年9月12日 下午3:44:34
	 */
	public static int getMonthSpace(Date date1, Date date2)
			throws ParseException {

		int result = 0;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();

		c1.setTime(date1);
		c2.setTime(date2);
		result = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);

		return result == 0 ? 1 : Math.abs(result);

	}

	/**
	 * 当前时间加上一个月
	 *
	 * @param date
	 * @return
	 * @author qiang.liu 2016年9月12日 下午4:35:01
	 */
	public static String getAddMonth(Date date, int num) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, num);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(cal.getTime());
	}

	/**
	 * 获取上一天
	 *
	 * @param date
	 * @return
	 */
	public static Date getPreDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 获取下一天
	 *
	 * @param date
	 * @return
	 */
	public static Date getNextDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, +1);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 获取上一月
	 *
	 * @param date
	 * @return
	 */
	public static Date getPreMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, -1);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 获取下一月
	 *
	 * @param date
	 * @return
	 */
	public static Date getNextMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, +1);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 获取日期当天的开始时间
	 *
	 * @param date
	 * @return
	 */
	public static Date getBeginDate(Date date) {
		if (date == null) {
			date = new Date();
		}
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = sdf1.format(date);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 获取获取当月的第一天
	 *
	 * @param date
	 * @return
	 */
	public static Date getMonthFirstDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, 1);//当月的第一天
		date = calendar.getTime();
		return date;
	}

	/**
	 * 获取两个日期相差分钟数
	 *
	 * @param start 开始时间
	 * @param end   结束时间
	 * @return
	 */
	public static long getMinutesOfTowDate(Date start, Date end) {
		if (start == null || end == null) {
			return 0;
		}
		long time = getDoubleDifference(start, end);
		return time / 1000 / 60;
	}
	public static String getAddDay(Date date,int num){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, num);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(cal.getTime());
	}
	public static String getAddDay(Date date,int num,String format){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, num);
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(cal.getTime());
	}
	public static String getAddMINUTE(Date date,int num){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MINUTE, num);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(cal.getTime());
	}



	/**
	 * 获取指定小时后的时间
	 * @param date
	 * @param amount
	 * @return
	 */
	public static Date getHourAdd(Date date, int amount) {

		Calendar cal = new GregorianCalendar();

		cal.setTime(date);

		cal.add(GregorianCalendar.HOUR, amount);

		return cal.getTime();

	}



	public static void main(String[] args) throws Exception{
		//logger.info(DateUtil.dateInterval("2016-06-23 16:04:42","2016-06-24 16:04:41",60*24*10));
		logger.info(DateUtil.getAddMonth(new Date(),3));
	}
}

